<template>
	<view class="container">
		<view class="logobox">
			<image :src="imgUrl+'login/logo.png'" mode="aspectFit" class="logo" style=""></image>
		</view>
		<view class="loginbox">
			<view class="form">
				<view class="mobile">
					<image :src="imgUrl+'login/mobile.png'" mode="aspectFit" class="icon"></image>
					<input placeholder="请输入手机号" type="number" v-model="form.phone" 
						border="none" maxlength="11"  class="input" clearable></input>
				</view>
				<view class="line">
					<u-line color="#EEEEEE"></u-line>
				</view>
				<!-- 请输入密码 -->
				<view class="password u-row-between" v-if="loginType=='password'">
					<view class="u-flex u-col-center u-flex-1">
						<image :src="imgUrl+'login/password.png'" mode="aspectFit" class="icon"></image>
						<input v-if="seen" type="text" placeholder="请输入密码(6~12位字母+数字)"
							maxlength="12" border="none" v-model="form.password"  class="input" 
							clearable></input>
						<input border="none" v-else  type="password" placeholder="请输入密码(6~12位字母+数字)"
								maxlength="12" v-model="form.password"  class="input" 
								clearable></input>
					</view>
				
					<!-- 显示隐藏图片 -->
					<view class="u-m-l-20">
						<image v-show='seen' @click="changeSeen" :src="imgUrl+'xianshi.png'" class="image_8" />
						<image v-show='!seen' @click="changeSeen" :src="imgUrl+'yingcang.png'" class="image_8" />
					</view>
				

				</view>
				<view class="codebox" v-if="loginType=='code'">
					<image :src="imgUrl+'login/code.png'" mode="aspectFit" class="icon"></image>

					<u-input type="text" placeholder="请输入验证码" maxlength="6" v-model="form.code"
						placeholderClass="placeholderClass" placeholder-style="" border="none" class="input" clearable style="width: 150px;">
					</u-input>
					<text class="text" @tap="getCode">{{tips}}</text>
					<view class="wrap">
						<u-toast ref="uToast"></u-toast>
						<u-code :seconds="seconds" @end="end" @start="start" ref="uCode" @change="codeChange"></u-code>

					</view>
				</view>
				<view class="line">
					<u-line color="#EEEEEE"></u-line>
				</view>
				<view class="code">
					<text class="text blue" v-if="loginType=='password'" @click="setType">验证码登录</text>
					<text class="text black" v-if="loginType=='code'" @click="loginType='password'">密码登录</text>
				</view>
				<view class="login" @click="login">
					<text class="text">登录</text>
				</view>
			</view>
		</view>
		<view class="action">
			<view class="other">
				<text @click="goReg">注册账号</text> <text class="line">|</text>
				<text @click="goForget">忘记密码</text>
				<text class="line">|</text>
				<text @click="goHome">游客登陆</text>
			</view>
		</view>
		<view class="u-flex u-row-center u-col-center quicklogin">
			<u-line length="83"></u-line><text class="text">快捷登录</text>
			<u-line length="83"></u-line>
		</view>
		<view class="wechat">
			<!-- <button open-type="getUserInfo" @getuserinfo="loginWechat('wechat')">授权登录</button> -->
			<image @click="loginWechat('wechat')" :src="imgUrl+'login/wechat.png'" mode="aspectFit" class="wechat-logo">
			</image>
		</view>
		<view class="agreement">
			<u-checkbox-group v-model="checked">
				<u-checkbox shape="circle" size="30" iconSize="30"></u-checkbox>
			</u-checkbox-group>
			<text>已阅读并同意</text> <text class="black" @click="regAgreement">《用户注册协议》</text>与<text class="black"
				@click="agreement">《隐私政策》</text>
		</view>

	</view>
</template>

<script>
	import {
		genTestUserSig
	} from '@/static/js/tim/GenerateTestUserSig.js';
	const app = getApp();
	import {
		mapMutations,
		mapActions,
		mapState,
		mapGetters
	} from 'vuex';
	// 调用微信登录方法
	import wechat from '@/shop/wechat/wechat';
	export default {
		name: "Login",
		components: {},
		data() {
			return {
				seen: false,
				type_text: "text",
				type_password: "password",
				checked: [],
				imgUrl: this.$IMG_URL,
				code: '',
				type: 'password',
				loginType: 'password',
				tips: '',
				seconds: 60,
				form: {
					phone: '',
					code: '',
					password: '',
					
					type: 1
				}
			}
		},
		computed: {
			...mapGetters(['isLogin'])
		},
		mounted() {
			if (this.isLogin) {
				this.go('/pages/index/my', true);
			}
		},
		methods: {

			changeSeen() { //密码显隐
				this.seen = !this.seen;
				console.log(this.form.password);
			},

			...mapActions(['getUserInfo']),
			goReg() {
				uni.navigateTo({
					url: "/pages/login/reg"
				})
			},
			goHome() {
				this.$store.dispatch('setHomeIndex', 0).then(()=>{
					uni.switchTab({
						url: '/pages/index/index'
					})
				})
				// 游客登陆跳转至首页
				
			},
			setType() {
				this.loginType = "code"
				this.type = "text"
			},
			goForget() {
				uni.navigateTo({
					url: "/pages/login/forget"
				})
			},
			// 微信授权登录 
			// 第三方登录
			async loginWechat(provider) {

				if (this.checked.length == 0) {
					this.$u.toast('请勾选已阅读《用户注册协议》与《隐私政策》');
					return;
				}

				const that = this;
				let res = ''
				switch (provider) {
					case 'wechat':
						res = await wechat.login();
						break;
					case 'alipay':
						break;
					case 'apple':
						res = await apple.appleIdOauth();
						break;
					default:
						break;
				}
				if (res) {
					console.log('res', res);
					if (res.isFirstWxLogin == 1) {
						uni.navigateTo({
							url: "/pages/index/bindWechat?unionid=" + res.unionId+"&openId="+res.openId
						})
					} else {
						if (res.token) {
							that.getUserInfo(res.token);
							this.$store.dispatch('setHomeIndex', 0);
							uni.switchTab({
								url: '/pages/index/my'
							})
						} else {
							uni.showToast({
								title: "数据异常"
							});
						}

					}
					// that.closeAuthModal();

				}
			},
			// 跳转
			regAgreement() {
				uni.navigateTo({
					url: "/pages/login/regAgreement"
				})
			},
			agreement() {
				uni.navigateTo({
					url: "/pages/login/agreement"
				})
			},
			login() {

				if (this.form.phone == '') {
					this.$u.toast('请输入手机号');
					return;
				} else {
					if (!uni.$u.test.mobile(this.form.phone)) {
						this.$u.toast('手机号码格式错误');
						return;
					}
				}
				if (this.loginType == 'code' && this.form.code == '') {
					this.$u.toast('请输入验证码');
					return;
				}
				if (this.loginType == 'code') {
					this.form.password = '';

				}
				if (this.loginType == 'password') {
					this.form.code = '';
					if ((this.form.password == '' || this.form.password.length < 6)) {
						this.$u.toast('密码至少6位(字母+数字)');
						return;
					} else {
						let reg = new RegExp(/^(?![^a-zA-Z]+$)(?!\D+$)/);

						if (!reg.test(this.form.password)) {
							this.$u.toast('密码格式错误,至少6位(字母+数字)');
							return;
						}
					}
				}

				if (this.checked.length == 0) {
					this.$u.toast('请勾选已阅读《用户注册协议》与《隐私政策》');
					return;
				}
				this.$http('user.login', this.form).then(r => {
					if (r.code == 200) {
						this.$u.toast(r.msg);
						this.getUserInfo(r.data.token);
						if(r.data.imUserId)
						{
						this.loginTim(r.data.imUserId);	
						}
						
						this.$store.dispatch('setHomeIndex', 0).then(()=>{
							this.go('/pages/index/my',true);
						});
						
					} else {
						this.$u.toast(r.msg);
					}
				});
			},


			loginTim(userID) {

				const SDKAppID = app.globalData.SDKAppID;
				const userSig = genTestUserSig(userID).userSig;
				console.log(`TUI-login | login  | userSig:${userSig} userID:${userID}`);
				// #ifdef  APP-PLUS
				uni.$aegis.reportEvent({
					name: 'platform',
					ext1: 'platform-APP',
					ext2: 'uniTuikitExternal',
					ext3: `${SDKAppID}`,
				})
				// #endif
				// #ifdef MP-WEIXIN  
				uni.$aegis.reportEvent({
					name: 'platform',
					ext1: 'platform-MP-WEIXIN',
					ext2: 'uniTuikitExternal',
					ext3: `${SDKAppID}`,
				})
				// #endif
				// #ifdef H5
				uni.$aegis.reportEvent({
					name: 'platform',
					ext1: 'platform-H5',
					ext2: 'uniTuikitExternal',
					ext3: `${SDKAppID}`,
				})
				// uni.showToast({
				// 	title: 'TUIKit 暂不支持 H5 / web ，请使用者自己完成兼容哦～ ',
				// 	icon: 'none',
				// 	duration: 3000
				// });
				// #endif
				app.globalData.userInfo = {
					userSig,
					userID
				};
				uni.setStorage({
					userInfo: app.globalData.userInfo
				})

				uni.setStorageSync(`TIM_${getApp().SDKAppID}_isTUIKit`, true);
				uni.$TUIKit.login({
					userID: userID,
					userSig: userSig
				}).then(() => {
					uni.$aegis.reportEvent({
						name: 'login',
						ext1: 'login-success',
						ext2: 'uniTuikitExternal',
						ext3: `${SDKAppID}`,
					})
				}).catch((error) => {
					uni.$aegis.reportEvent({
						name: 'login',
						ext1: `login-failed#error:${error}`,
						ext2: 'uniTuikitExternal',
						ext3: `${SDKAppID}`,
					})
				})

				// 登录原生插件
				// #ifdef APP-PLUS
				if (typeof(uni.$TUICalling) == 'undefined') {
					// uni.showToast({
					// 	title: '如果需要音视频功能，请集成插件使用真机运行并且自定义基座调试哦～',
					// 	icon: 'none',
					// 	duration: 3000
					// });
					console.log(
						'请使用真机运行并且自定义基座调试，否则影响音视频功能～ 插件地址：https://ext.dcloud.net.cn/plugin?id=7097 , 调试地址：https://nativesupport.dcloud.net.cn/NativePlugin/use/use'
					);
				} else {
					uni.$TUICalling.login({
							sdkAppID: SDKAppID,
							userID: userID,
							userSig: userSig
						},
						res => {
							console.log(JSON.stringify(res.msg));
							uni.showToast({
								title: 'login',
								icon: 'none'
							});
						}
					);
				}

				// #endif
				if (this.path && this.path !== 'undefined') {
					uni.redirectTo({
						url: this.path
					});
				} else {
					uni.switchTab({
						url: '/pages/index/my'
					});
				}
			},
			codeChange(text) {
				this.tips = text;
			},
			getCode() {
				if (this.form.phone) { //判断是否输入手机号 
					if (this.$refs.uCode.canGetCode) {
						uni.showLoading({
							title: '正在获取验证码'
						})
						this.$http('user.code', {
							phone: this.form.phone
						}).then(r => {
							if (r.code == 200) {
								this.form.code = r.data;
								uni.hideLoading();
								// 这里此提示会被this.start()方法中的提示覆盖
								uni.$u.toast('验证码已发送');
								// 通知验证码组件内部开始倒计时
								this.$refs.uCode.start();
							} else {
								uni.$u.toast(r.msg);
							}
						});

					} else {
						uni.$u.toast('倒计时结束后再发送');
					}
				} else {
					uni.$u.toast('请输入手机号码');
				}

			},
			end() {
				uni.$u.toast('请输入验证短信');
			},
			start() {
				uni.$u.toast('我们已经发送了验证短信到你的手机');
			}

		}
	}
</script>

<style scoped lang="scss">
	.input {
		width: 440rpx;
		font-size: 32rpx;
		border: 0;
	}
/deep/  .placeholderClass{
					 font-size: 32rpx;
					 font-family: PingFang SC;
					 font-weight: 400;
					 line-height: 34rpx;
					 color: #BFBFBF;
					 opacity: 1;
	}
	.image_8 {
		// margin-left: 140rpx;
	
	   margin-top: 6rpx;
	    width: 44rpx;
		height: 44rpx;
	}

	/deep/ .input-placeholder {
		font-size: 32rpx;
		color: #D4D6DC;
	}


	@import './login.scss'
</style>
